package com.situ.mall.base.service.impl;


import com.situ.mall.base.entity.Member;
import com.situ.mall.base.exception.NoLoginException;
import com.situ.mall.base.mapper.CartMapper;
import com.situ.mall.base.util.OrderSessionUtil;
import com.situ.mall.base.entity.Cart;

import com.situ.mall.base.service.ICartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.situ.mall.base.vo.CartVO;
import com.situ.mall.base.vo.OrderVO;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author darling
 * @since 2023-04-02
 */

@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {

    @Override
    public void addToCart(Integer productId) {

        Member m = OrderSessionUtil.getCurrent();
        if (m == null) { // 还没登录
            throw new NoLoginException();
        }

        Cart c = baseMapper.selectByMemberIDAndProductID(m.getId(), productId);

        // 判断此产品是否之前加入过购物车
        // 如果没加入过
        if (c == null) {

            Cart cart = new Cart();
            cart.setCount(1);
            cart.setProductId(productId);
            cart.setCreatetime(LocalDateTime.now());

            cart.setMemberId(m.getId()); // 当前会员ID
            baseMapper.insert(cart);
        } else {
            // 如果加入过，把对应的数据数量加 1
            baseMapper.updateAmount(c.getId());
        }


    }

    @Override
    public List<CartVO> doList() {

        // 当前登录的会员
        Member m = OrderSessionUtil.getCurrent();
        return baseMapper.selectCartList(m.getId());


    }

    @Override
    public void doDel(Integer cartId) {
        baseMapper.doDelById(cartId);
    }

    @Override
    public void add(Integer id) {
        baseMapper.add(id);
    }

    @Override
    public void sub(Integer id) {
        baseMapper.sub(id);
    }

    @Override
    public List<OrderVO> doListByIds(String ids) {
        List<OrderVO> list = new ArrayList<>();
        for (String id: ids.split(",")) {
            OrderVO vo = baseMapper.doListByIds(Integer.parseInt(id));
            BigDecimal b = new BigDecimal(vo.getCount());
            vo.setSum(b.multiply(vo.getPrice()));
            list.add(vo);
        }
        return list;
    }


}
